import {
  uploadJcmcFileApi,
  saveJcmcApi,
  getJcmxPage,
  deleteJcmxApi,
  updateJcmxApi
} from './api/index'
import { exportModelZip } from '@/api/download.js'
import * as echarts from 'echarts'
import { saveAs } from 'file-saver'
import { modelBuildMethodOption,aiFrameworkOption } from '@/assets/data/pathInfo'
export default {
  components: {},
  data() {
    return {
      formInline: {},
      labelPosition: 'right',
      formLabelAlign: {
        fileInfo: {
          fileName: '',
          filePath: ''
        },
        mxgjfs: ''
      },
      options: [
        {
          value: '值1',
          label: '选项1'
        },
        {
          value: '值2',
          label: '选项2'
        }
      ],
      kfyyOptions: [
        {
          value: 'Java',
          label: 'Java'
        },
        {
          value: 'Python',
          label: 'Python'
        },
        {
          value: 'C/C++',
          label: 'C/C++'
        }
      ],
      tableData: [],
      currentPage3: 5,
      dialogVisible: false,
      modelAndAssessBool: 0,
      pageCurrent: 0,
      pageSize: 10,
      total: 0,
      multipleSelection: [],
      mxCommit: false,
      rules: {
        mxmc: [{ required: true, message: '请输入模型名称', trigger: 'blur' }],
        aikj: [{ required: true, message: '请选择AI框架', trigger: 'change' }],
        yxhj: [{ required: true, message: '请输入运行环境', trigger: 'blur' }],
        jcsd: [
          { required: false, message: '请输入决策速度', trigger: 'change' }
        ],
        sfmc: [{ required: true, message: '请输入算法名称', trigger: 'blur' }],
        kfyy: [
          { required: true, message: '请输入开发语言', trigger: 'change' }
        ],
        bbxx: [{ required: true, message: '请输入版本信息', trigger: 'blur' }],
        jczql: [
          { required: false, message: '请输入决策准确率', trigger: 'blur' }
        ],
        mxlx: [{ required: true, message: '请输入模型类型', trigger: 'blur' }],
        mxgjfs: [
          { required: true, message: '请选择模型构建方式', trigger: 'change' }
        ]
      },
      addModalTitle: '添加模型',
      isFileUploaded: false,
      modelBuildMethodOption,
      aiFrameworkOption
    }
  },
  computed: {},
  created() {},
  mounted() {
    this.getJcmxPageData(this.formInline)
  },
  methods: {
    // 导出决策模型
    async exportJcmxData() {
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请选择要导出的数据')
      }
      if (this.multipleSelection.length > 1) {
        return this.$message.warning('每次只可以导出一条数据')
      }

      this.$message.warning('正在导出')

      const rowValue = this.multipleSelection[0]

      try {
        window.open(
          window.ipConfig.api +
            '/ybgl/jcmx/downloadZip?mxId=' +
            rowValue.mxID +
            '&mxType=JCMX'
        )
      } catch (error) {
        console.error('下载Excel失败:', error)
      }
    },
    initFromLabel() {
      this.formLabelAlign = {
        fileInfo: {
          fileName: '',
          filePath: ''
        }
      }
    },
    // 编辑按钮
    sampleEdit(row) {
      Object.keys(row).forEach(key => {
        this.$set(this.formLabelAlign, key, row[key])
      })
      this.dialogVisible = true
      this.modelAndAssessBool = 0
      this.addModalTitle = '编辑模型'
      this.mxCommit = false
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getJcmxPageData(this.formInline)
    },
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.getJcmxPageData(this.formInline)
    },
    getJcmxPageData(data) {
      const query = {
        ...data,
        pageCurrent: this.pageCurrent,
        pageSize: this.pageSize
      }
      getJcmxPage(query).then(res => {
        if (res.data.code === 200) {
          const data = res.data
          this.tableData = data.data.records
          this.total = data.data.total
        }
      })
    },
    // 删除决策模型数据
    deleteJcmxData() {
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请选择需要删除的数据')
      }

      const idList = []
      this.multipleSelection.forEach(item => {
        idList.push(item.mxID)
      })
      const data = {
        ids: idList
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        deleteJcmxApi(data).then(res => {
          if (res.data.code === 200) {
            this.$message.success('操作成功')
            this.getJcmxPageData(this.formInline)
          } else {
            this.$message.error('操作失败')
          }
        })
      })
    },
    // 勾选回调方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 选择文件上传
    async selectWjButton(e) {
      let that = this
      // 点击后禁用上传按钮
      that.isFileUploaded = true
      function callbackFn(event) {
        if (event.target.files.length > 0) {
          // 确保只执行一次上传
          that.mxCommit = true
          const file = event.target.files[0]
          that.formLabelAlign.fileInfo.fileName = file.name

          const formData = new FormData()
          formData.append('file', file)

          uploadJcmcFileApi(formData)
            .then(res => {
              if (res.data.code === 200) {
                that.formLabelAlign.fileInfo.filePath = res.data.message
                that.$message.success('操作成功')
                that.isFileUploaded = false // 更新状态
                that.mxCommit = false
                // 移除事件监听，防止重复触发
                changeFile.removeEventListener('change', callbackFn, false)
              } else {
                that.$message.error('操作失败')
              }
            })
            .catch(error => {
              console.error('上传文件时发生错误:', error)
              that.$message.error('上传文件失败')
            })
        }
      }
      // 触发文件选择
      const changeFile = document.getElementById('fileUpload')
      changeFile.removeEventListener('change', callbackFn, false)
      changeFile.click()
      // 监听文件选择变化
      changeFile.addEventListener('change', callbackFn, false)
    },
    // 模型评估和保存决策模型
    mxpgAndSaveJcmxData() {
      // 保存决策模型
      if (this.modelAndAssessBool !== 0) return false

      this.$refs.jcmxFrom.validate(valid => {
        if (!valid) return false
        if (this.formLabelAlign.fileInfo.fileName == '') {
          this.$message.error('请上传模型文件')
          return false
        }
        // 保存决策模型
        if (this.formLabelAlign.mxID && this.formLabelAlign.mxID !== '') {
          this.updateJcmxData()
        } else {
          this.saveJcmxData()
        }
      })
    },
    // 重置
    onReset() {
      this.pageCurrent = 1
      this.formInline = {}
      this.getJcmxPageData(this.formInline)
    },
    // 取消决策模型弹窗
    cancelJcmxDialog() {
      // 保存决策模型
      if (this.modelAndAssessBool == 0) {
        this.initFromLabel()
        // 清空之前上传的文件
        document.getElementById('fileForm').reset()
      }
      this.dialogVisible = false
    },
    // 保存决策模型信息
    saveJcmxData() {
      saveJcmcApi(this.formLabelAlign).then(res => {
        if (res.data.code === 200) {
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.getJcmxPageData(this.formInline)
          this.mxCommit = true
        } else {
          this.$message.error('操作失败')
        }
      })
    },
    // 更新决策模型数据
    updateJcmxData() {
      updateJcmxApi(this.formLabelAlign).then(res => {
        if (res.data.code === 200) {
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.getJcmxPageData(this.formInline)
          this.mxCommit = true
        } else {
          this.$message.error('操作失败')
        }
        // 清空之前上传的文件
        document.getElementById('fileForm').reset()
      })
    },
    onSubmit() {
      this.pageCurrent = 1
      this.getJcmxPageData(this.formInline)
    },
    startTrain(row) {
      sessionStorage.setItem('decisionInfo', JSON.stringify(row)) // 使用url传参会遇到[object,object]的问题，存到会话中
      this.$router.push({
        path: '/model-management/decisionModel-model/train',
        query: {
          id: row.mxID
        }
      })
    },
    addModelAndAssess(bool) {
      this.dialogVisible = true
      this.initFromLabel()
      this.modelAndAssessBool = bool

      if (this.$refs.jcmxFrom) {
        this.$refs.jcmxFrom.resetFields()
      }
      this.addModalTitle = '添加模型'
      if (bool) {
        this.$nextTick(() => {
          this.initChart()
        })
      }
    },
    initChart() {
      let chartDom = document.getElementById('chart')
      let myChart = echarts.init(chartDom)
      let option
      option = {
        xAxis: {
          type: 'category',
          data: ['1', '2', '3', '4', '5'],
          axisLine: {
            lineStyle: {
              color: '#677488'
            }
          },
          axisLabel: {
            textStyle: {
              color: '#fff'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '(得分)',
          nameTextStyle: {
            color: '#fff',
            align: 'right'
          },
          splitLine: { show: false },
          axisLine: {
            lineStyle: {
              color: '#677488'
            }
          },
          axisLabel: {
            textStyle: {
              color: '#fff'
            }
          }
        },
        series: [
          {
            data: [90, 70, 50, 80, 70],
            type: 'pictorialBar',
            symbol: 'triangle',
            barCategoryGap: '0%',
            itemStyle: {
              color: function(params) {
                const colormap = [
                  '#3fb9b1',
                  '#3061df',
                  '#898831',
                  '#4b7c10',
                  '#81560f'
                ]
                return colormap[params.dataIndex]
              },
              opacity: 0.8
            }
          }
        ]
      }
      option && myChart.setOption(option)
    }
  }
}
